package com.ysstech.dataway.thread;


import com.ysstech.common.enums.YssEnum;
import com.ysstech.common.service.DicvalueService;
import com.ysstech.dataway.entity.Dataway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;

@Slf4j
@Component
public class DatawayMainGenerator {
    @Autowired
    private List<DatawayGenerateService> datawayGenerateService;
    @Autowired
    private DicvalueService dicvalueService;

    /**
     * 处理数据
     *
     * @return
     * @throws Exception
     */

    public void renewValuation(List<String> list, Dataway dataway) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(YssEnum.YSS_DEFAULT_DATE_TIME.getCode());
        Date startDate = sdf.parse(dataway.getStartDate());   // 起始日期
        Date endDate = sdf.parse(dataway.getEndDate());  // 结束日期
        Date tmpDate = startDate;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        Boolean falg = true;
        while (falg && tmpDate.getTime() < endDate.getTime()) {
            falg = ThreadSubmit(list, dataway);
        }
    }

    private Boolean ThreadSubmit(List<String> list, Dataway dataway) throws Exception {
        List<Future> futureList = new ArrayList<>();
        Boolean falg = true;
        list.forEach(account -> {
            datawayGenerateService.forEach(vg -> {
                DatawayThread ht = new DatawayThread(vg);
                ThreadPool.getThreadPool().submit(ht);
            });
        });
        while (futureList.stream().filter(f -> !f.isDone()).count() > 0) {
            Thread.sleep(1000);
        }
        for (Future<Boolean> future : futureList) {
            if (!future.get()) {
                falg = false;
                break;
            }
        }
        return falg;
    }

}
